package com.example.demo040801;

import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.demo040801.Retrofit.RetrofitClient;
import com.example.demo040801.adapter.BingImageAdapter;
import com.example.demo040801.api.ApiService;
import com.example.demo040801.entity.BingImage;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    private CompositeDisposable compositeDisposable = new CompositeDisposable();
    private RecyclerView recyclerView;
    private BingImageAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new BingImageAdapter();
        recyclerView.setAdapter(adapter);

        fetchBingImages();
    }

    private void fetchBingImages() {
        ApiService apiService = RetrofitClient.getClient().create(ApiService.class);
        compositeDisposable.add(apiService.getBingImages()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        this::handleResponse,
                        this::handleError
                )
        );
    }

    private void handleResponse(List<BingImage> bingImages) {
        adapter.setBingImages(bingImages);
    }

    private void handleError(Throwable error) {
        Toast.makeText(this, "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        compositeDisposable.clear();
    }
}